package com.frxuexi.docment

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.frxuexi.docment.intent.DocIntent
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch

class DocViewModel:ViewModel() {
    val docRepository by lazy { DocRepository() }

    val docChannel = Channel<DocIntent>(Channel.UNLIMITED)

    private var _docSatte = MutableStateFlow<DocState>(DocState.onLoading)
    val docState: StateFlow<DocState>
        get() = _docSatte

    init {
        viewModelScope.launch {
            docChannel.consumeAsFlow().collect{
                when(it)
                {
                    is DocIntent.getFiles->{
                        getFiles()
                    }
                    is DocIntent.deleteFile->{
                        deleteFile(it.fildId)
                    }
                    else->{}
                }
            }
        }


    }

    fun getFiles(){
        val map = hashMapOf<String, Any>(Pair("userId", 1), Pair("page", 1))
        viewModelScope.launch {
            docRepository.getFiles(map).flowOn(Dispatchers.IO)
                .catch {
                    it.printStackTrace()
                }.collect{
                    if(it.statusCode==200){
                        _docSatte.value=DocState.onSuccess(it.data)
                    }else{
                        _docSatte.value=DocState.onError(it.msg!!)
                    }
                }
        }
    }

    fun deleteFile(fildId:Int){
        viewModelScope.launch {
            docRepository.deleteFile(fildId = fildId).flowOn(Dispatchers.IO)
                .catch {
                    it.printStackTrace()
                }
                .collect{
                    if(it.statusCode==200){
                        _docSatte.value=DocState.onDeleteSuccess
                    }else{
                        _docSatte.value=DocState.onError(it.msg!!)
                    }
                }
        }
    }
}